<script setup lang="ts">
/***********************
 * 模块导入
 ***********************/
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

/***********************
 * 类型定义
 ***********************/
interface Tab {
  name: string
  path: string
  label: string
  icon?: string
}

interface ContextMenuState {
  visible: boolean
  x: number
  y: number
  currentTag: Tab | null
}

type TabOperation = 'left' | 'right' | 'other' | 'all'

/***********************
 * 组合式 API 初始化
 ***********************/
const store = useStore()
const router = useRouter()
const route = useRoute()

/***********************
 * 响应式状态
 ***********************/
const contextMenu = ref<ContextMenuState>({
  visible: false,
  x: 0,
  y: 0,
  currentTag: null
})

/***********************
 * 计算属性
 ***********************/
const tabsList = computed<Tab[]>(() => store.state.tabsList || [])
const currentRouteName = computed(() => route.name)
const homeTabIndex = computed(() => tabsList.value.findIndex(t => t.name === 'home')) // 首页固定索引[1](@ref)

/***********************
 * 上下文菜单控制
 ***********************/
const showContextMenu = (event: MouseEvent, tag: Tab) => {
  event.preventDefault()
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    currentTag: tag
  }
}

const closeContextMenu = () => {
  contextMenu.value.visible = false
}

/***********************
 * 标签页操作逻辑
 ***********************/
const closeTags = (operation: TabOperation) => {
  const currentTag = contextMenu.value.currentTag
  if (!currentTag || homeTabIndex.value === -1) return

  const currentIndex = tabsList.value.findIndex(t => t.name === currentTag.name)
  if (currentIndex === -1) return

  let newTabs: Tab[] = []
  
  switch(operation) {
    case 'left':
      newTabs = [
        tabsList.value[homeTabIndex.value], 
        ...tabsList.value.slice(currentIndex)
      ]
      break
    case 'right':
      newTabs = [
        tabsList.value[homeTabIndex.value],
        ...tabsList.value.slice(homeTabIndex.value + 1, currentIndex + 1)
      ]
      break
    case 'other':
      newTabs = currentTag.name === 'home' 
        ? [tabsList.value[homeTabIndex.value]] 
        : [tabsList.value[homeTabIndex.value], currentTag]
      break
    case 'all':
      newTabs = [tabsList.value[homeTabIndex.value]]
      break
  }

  store.commit('tabs/updateTabs', newTabs)
  closeContextMenu()

  // 路由跳转保护（优先跳转首页）
  if (!newTabs.some(t => t.name === currentRouteName.value)) {
    router.push(newTabs.find(t => t.name === 'home')?.path || '/')
  }
}

/***********************
 * 页面刷新控制
 ***********************/
const refreshTab = (fullReload = false) => {
  closeContextMenu()
  if (fullReload) {
    window.location.reload()
    return
  }
  
  const currentTag = contextMenu.value.currentTag
  if (!currentTag) return

  router.replace({
    path: currentTag.path,
    query: { t: Date.now().toString() }
  })
}
</script>

<template>
  <div class="tab-container">
    <el-tag
      v-for="tag in tabsList"
      :key="tag.name"
      :closable="tag.name !== 'home'"
      :effect="currentRouteName === tag.name ? 'dark' : 'plain'"
      class="tab-item"
      @click="router.push(tag.path)"
      @close="store.commit('tabs/closeTab', tag)"
      @contextmenu.prevent="showContextMenu($event, tag)"
    >
      {{ tag.label }}
    </el-tag>

    <teleport to="body">
      <div 
        v-show="contextMenu.visible"
        class="context-menu"
        :style="{ left: `${contextMenu.x}px`, top: `${contextMenu.y}px` }"
        @click.capture="closeContextMenu"
      >
        <!-- 首页菜单 -->
        <template v-if="contextMenu.currentTag?.name === 'home'">
          <div class="menu-item" @click.stop="refreshTab()">刷新标签页</div>
          <div 
            class="menu-item"
            :class="{ disabled: tabsList.length === 1 }"
            @click.stop="closeTags('other')"
          >
            关闭其他
          </div>
        </template>

        <!-- 非首页菜单（完整功能） -->
        <template v-else>
          <div class="menu-item" @click.stop="refreshTab()">刷新当前页</div>
          <div class="menu-item" @click.stop="refreshTab(true)">刷新所有页</div>
          <div class="menu-divider" />
          
          <div 
            class="menu-item"
            :disabled="homeTabIndex >= tabsList.indexOf(contextMenu.currentTag!)"
            @click.stop="closeTags('left')"
          >
            关闭左侧
          </div>
          
          <div 
            class="menu-item"
            :disabled="tabsList.indexOf(contextMenu.currentTag!) === tabsList.length - 1"
            @click.stop="closeTags('right')"
          >
            关闭右侧
          </div>
          
          <div 
            class="menu-item"
            :disabled="tabsList.length - homeTabIndex <= 2"
            @click.stop="closeTags('other')"
          >
            关闭其他
          </div>
          
          <div 
            class="menu-item danger"
            @click.stop="closeTags('all')"
          >
            关闭所有
          </div>
        </template>
      </div>
    </teleport>
  </div>
</template>

<style scoped>
.menu-item[disabled] {
  opacity: 0.6;
  pointer-events: none;
  filter: grayscale(100%);
}

.tab-container {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 16px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;

  .tab-item {
    cursor: context-menu;
    transition: all 0.3s ease;

    &[effect="dark"] {
      background: var(--el-color-primary);
      border-color: var(--el-color-primary);
      color: #fff;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
  }
}

.context-menu {
  position: fixed;
  z-index: 9999;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  min-width: 160px;
  padding: 8px 0;


   /* 新增危险操作样式 */
  .danger {
    color: #f56c6c;
    &:hover {
      background: #fef0f0;
    }
  }
  .menu-divider {
    height: 1px;
    background: #ebeef5;
    margin: 6px 0;
  }

  .menu-item {
    padding: 8px 16px;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }

    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
      background: transparent;
    }
  }
}
/* 标签容器动画 */
.tab-item {
  transition: 
    transform 0.3s ease,
    box-shadow 0.3s ease; /* 复合动画效果 */
  
     transition: 
    transform 0.25s cubic-bezier(0.4, 0, 0.2, 1),
    box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
}
</style>